﻿using E.Tool;
using System;
using System.Collections;
using System.Collections.Generic;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.Tilemaps;

public class Role : NetworkBehaviour
{
    public FloatProperty health;
    private TemporaryUI ui;
    private CameraManager cm;
    private TilemapManager tm;

    private void Start()
    {
        health = new FloatProperty(10, 0, 10);

        ui = FindFirstObjectByType<TemporaryUI>();
        cm = FindFirstObjectByType<CameraManager>();
        tm = FindFirstObjectByType<TilemapManager>();

        // 检测是否本地玩家，是否已生成
        if (!IsOwner || !IsSpawned) return;

        // 相机跟随本地玩家
        cm.SetFollowTarget(transform);
    }

    private void Update()
    {
        // 检测是否本地玩家，是否已生成
        if (!IsOwner || !IsSpawned) return;

        // 显示本地玩家坐标
        ui.UpdatePosition(transform.position);

        // 涂抹路过的瓦片
        if (Input.GetKey(KeyCode.Space))
        {
            int x = Convert.ToInt32(transform.position.x);
            int y = Convert.ToInt32(transform.position.y);
            SetTileServerRpc(x, y, 0);
        }
    }


    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.TryGetComponent(out Area area))
        {
            if (area.owner == this)
            {
                StartCoroutine(Do());
                Debug.Log("开始恢复生命");
            }
            area.AddCaptureRole(this);
        }
    }

    private void OnTriggerStay2D(Collider2D collision)
    {
        //Debug.Log("!!");
    }

    private void OnTriggerExit2D(Collider2D collision)
    {
        if (collision.TryGetComponent(out Area area))
        {
            if (area.owner == this)
            {
                StopCoroutine(Do());
                Debug.Log("结束恢复生命");
            }
            area.RemoveCaptureRole(this);
        }
    }

    IEnumerator Do()
    {
        while (true)
        {
            yield return new WaitForSeconds(1);
            health.AddTarget(1);
        }
    }



    [ServerRpc]
    /// <summary>
    /// 设置瓦片
    /// </summary>
    /// <param name="x">横坐标</param>
    /// <param name="y">纵坐标</param>
    /// <param name="tileIndex">瓦片索引</param>
    public void SetTileServerRpc(int x, int y, int tileIndex)
    {
        foreach (NetworkClient client in NetworkManager.Singleton.ConnectedClientsList) 
        {
            client.PlayerObject.GetComponent<Role>().SetTileClientRpc(x, y, tileIndex);
        }
    }

    [ClientRpc]
    /// <summary>
    /// 设置瓦片
    /// </summary>
    /// <param name="x">横坐标</param>
    /// <param name="y">纵坐标</param>
    /// <param name="tileIndex">瓦片索引</param>
    public void SetTileClientRpc(int x, int y, int tileIndex)
    {
        tm.SetTile(x, y, tileIndex);
    }
}
